package wang.unclecat.dialog_ohos;

import ohos.agp.components.*;
import wang.unclecat.catdialog.SimpleItemSelectHandler;

import java.util.List;

/**
 * 自定义的Provider
 *
 * @author: 喵叔catuncle
 */
public class MyItemProvider extends BaseItemProvider {

    public MyItemProvider(List<String> dataList) {
        this.dataList = dataList;
    }

    private List<String> dataList;

    private SimpleItemSelectHandler itemSelectHandler = new SimpleItemSelectHandler() {
        @Override
        protected void doSelect(Component component, boolean b) {
            if (component != null) {
                component.setSelected(b);
                MyItemProvider.ViewHolder viewHolder = (MyItemProvider.ViewHolder) component.getTag();
                if (viewHolder != null) {
                    if (b) {
                        viewHolder.mark.setPixelMap(ResourceTable.Media_select);
                    } else {
                        viewHolder.mark.setPixelMap(null);
                    }
                }
            }
        }
    };

    @Override
    public int getCount() {
        return dataList.size();
    }

    @Override
    public Object getItem(int i) {
        return dataList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public Component getComponent(int i, Component component, ComponentContainer componentContainer) {
        ViewHolder viewHolder;

        if (component == null) {
            component = LayoutScatter.getInstance(componentContainer.getContext()).parse(ResourceTable.Layout_my_list_item, null, false);
            viewHolder = new ViewHolder();
            viewHolder.text = (Text) component.findComponentById(ResourceTable.Id_item_index);
            viewHolder.mark = (Image) component.findComponentById(ResourceTable.Id_mark);
            component.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder)component.getTag();
        }

        viewHolder.text.setText(getItem(i).toString());

        return component;
    }

    public void handleSelect(ListContainer listContainer, int preIndex, int index) {
        itemSelectHandler.handleSelect(listContainer, preIndex, index);
    }

    private static final class ViewHolder {
        Text text;
        Image mark;
    }


}
